$(function() {
//Declare variable
var     tips = $( ".validateTips" ),
        button_name="",
        url="model.php", 
        ID="",
        Order_col='default',
        rowSelect="" ,
        g_page=1,
        order_type='desc';
        

        //Load First page
        LoadData(1,true,'default','desc');
                                
         
    
        $("a.sort").click(function(){
            var id = $(this).attr('id');
            order_type =$("#ord").val();
            //  alert(type);
            Order_col=id;
            LoadData (1,true, Order_col, order_type);
            
            if (order_type=='desc')
                $("#ord").val('asc');
            else{
                $("#ord").val('desc');
            }
     
        });
        
        //Show Loading bar          
        function showLoader(){
            $( "#resultData tbody:first" ).prepend( "<tr>"
                        +"<td colspan='6' class='search-background'>"
                        +"<label><img src='images/ajax-loader.gif'/></label>"
                        +"</td>"
                        +"</tr>" ); 
             $('.search-background').fadeIn(900,0);
        }
        //Hide Loading bar          
        function hideLoader(){
            $('.search-background').fadeOut(300);
            $( "#resultData tbody tr" ).remove();
        };
        
        // Search Click
        $("#btnSearch").click(function(){
            LoadData(1,true,'default','desc');
        });
        
       
        
      
    $(".btnDelete").live('click',function(){
        //var table  = $(this).parent().parent().parent();
        var rowSelect = $(this).parent().parent();
        var oid  =rowSelect.find("td").eq(1).html();
        var irow  =rowSelect.find("td").eq(0).html();
          
        $("#dialog-confirm").dialog("open");
        $("#dialog-confirm").dialog("option","buttons", {
            "ยืนยัน": function() {
                $.post(url, {'m':'delnews','i':oid}, function(data){
                  
                    var obj=eval("(" + data + ")");
                    if (data==1){
                            
                            LoadData(g_page,true, Order_col, order_type);
                            $("#dialog-confirm").dialog( "close" );
     
                        }
                    });
                    
                },
                "ยกเลิก": function() {
                        $( this ).dialog( "close" );
            }
        });
    });

    
    //Confirm Dialog
    $( "#dialog-confirm" ).dialog({
        resizable: false,
        height:160,
        zIndex:9999,
        autoOpen: false,
        modal: true
    });
    
    $( "#dialog:ui-dialog" ).dialog( "destroy" );
    
    function checkRequireControlAcc(){
            var bValid=true;
            bValid = bValid && checkInputFileAcc( $("#txtUsername"), "Username",1);
            bValid = bValid && checkInputFileAcc( $("#txtPassword"), "Password",1);
            bValid = bValid && checkInputFileAcc( $("#txtConfirmPassword"), "Confirm Password",1);
            bValid = bValid && compare($("#txtPassword") , $("#txtConfirmPassword") )
            return bValid;
    }
    
    function compare(b1 , b2){
        if (b1.val() != b2.val()){
            b2.addClass( "ui-state-error" );
            updateTipsAcc( " กรุณากรอก Confirm Password ใหม่อีกครั้ง " );
            return false;
        } else {
            return true;
        }
    }
    
    function checkInputFileAcc( o, n, min ) {
        if (o.val().length < min ) {
            o.addClass( "ui-state-error" );
            updateTipsAcc( "Please input " + n + "." );
            return false;
        } else {
            return true;
        }
    }
    
    function checkLengthAcc( o, n, min, max ) {
        if ( o.val().length > max || o.val().length < min ) {
            o.addClass( "ui-state-error" );
            updateTipsAcc( "Length of " + n + " must be between " +
                min + " and " + max + "." );
            return false;
        } else {
            return true;
        }
    }
    
    function updateTipsAcc( t ) {
        tips
            .text( t )
            .addClass( "ui-state-highlight" );
        setTimeout(function() {
            tips.removeClass( "ui-state-highlight", 1500 );
        }, 500 );

    }   
        //b=false , don't gennerate paging
        function LoadData(page,b, order, typeOrder){
            $( "#resultData tbody tr" ).remove();
            //Show loading
            showLoader();
            //set criteria
         
             var datefrom ='';
             var dateto='';
 
             var title=$('#txtTitle').val();
             
        
            datefrom =$('#txtOrderFrom').val();
            dateto=$('#txtOrderTo').val()
            
          
            var dataSet={'m':'news'
                        ,'from':datefrom
                        ,'to':dateto
                        ,'order':order
                        ,'typeOrder':typeOrder
                        ,'page':page
                         ,'title':title
                        ,'rows':$("#txtPage").val()
                        };              
             //Post             
            $.post(url, dataSet ,function(data){
            //alert(data);
                var obj=eval("(" + data + ")");
                
                hideLoader();
                $( "#resultData tbody tr" ).remove();
                $( "#rowCount" ).attr('innerHTML',obj['rows']);
                $( "#resultData tbody" ).append(obj['data']);
                
                $( "#resultAmt tbody tr" ).remove();
                $("#resultAmt tbody").append(obj['data_amt']);
                //set page
                if (b){
                 
                    if (parseInt(obj['totalpage'])>1){
                        $("#paging_btn").show();
                        setPaging(parseInt(obj['totalpage']));
                    }else{
                        $("#paging_btn").hide();
                    }   
                     
                }
            //  $("#"+page).css({'background-color' : '#006699'});
            });
        }
    
        function setPaging(iTotal){
                     $("#paging_btn").paginate({
                    count       : iTotal,
                    start       : 1,
                    display     : $("#txtPage").val(),
                    border                  : false,
                    text_color              : '#888',
                    background_color        : '#EEE',   
                    text_hover_color        : 'blue',
                    background_hover_color  : '#CFCFCF',
                    mouse                   : 'press',
                    onChange                : function(page){
                                                
                                                LoadData(page,false ,Order_col,$("#ord").val());
                                              }
                });
            }   
});
    